
import React, { useCallback, useMemo, useRef, useState } from "react";
import {message} from 'antd'
import useUserMedia  from "./useUserMedia";

const DEFAULT_CONSTRAINTS = {
    sampleRate: 16000,
    sampleSize: 16,
    channelCount: 1,
};
export default (props: any) => {
    const {constraints, recordCallback, onRecordError} = props;
    const defaultSample = constraints?.sampleRate || DEFAULT_CONSTRAINTS.sampleRate;
    const precessorRef = useRef<any>(null)
    const sampleRateRef = useRef<any>(null);
    const recordingRef = useRef<boolean>(false);
    const mediaStreanSourceRef = useRef<MediaStreamAudioSourceNode | null>()
    const recordCallbackRef = useRef<any>(false);
    recordCallbackRef.current = recordCallback;

    const audioContext: AudioContext = useMemo(() => {
        return new (window.AudioContext || (window as any)?.webkitAudioContext)({
            sampleRate: defaultSample
        })
    }, [defaultSample])

    const handleAudioProcessor = useCallback((stream: MediaStream) => {
        if(recordingRef.current && recordCallbackRef.current) {
            recordCallbackRef.current(stream, sampleRateRef.current);
        }
    }, [])
    
    const success = useCallback((stream: MediaStream) => {
        recordCallbackRef.current(stream, sampleRateRef.current);
        // 让录音得到的音频流变得可以被处理，例如播放，暂停。
        const mediaStreanSource: MediaStreamAudioSourceNode = audioContext.createMediaStreamSource(stream);
        mediaStreanSourceRef.current = mediaStreanSource

        const precessor = audioContext.createScriptProcessor(1024, 1, 1);
        precessorRef.current = precessor
        mediaStreanSource.connect(precessor);
        precessor.connect(audioContext.destination);
        sampleRateRef.current = audioContext.sampleRate;

        if(audioContext.state === 'suspended') {
            audioContext.resume();
        }
        handleAudioProcessor(stream);
        precessor.onaudioprocess = handleAudioProcessor
    }, [handleAudioProcessor, audioContext])

    const handleDfaultError = () => {
        message.info('请配置https')
    }

    const {stop, start, recording} = useUserMedia({
        video: false,
        audio: {
            ...DEFAULT_CONSTRAINTS,
            ...constraints
        }
    }, success, onRecordError || handleDfaultError)
    recordingRef.current = recording;
    return {
        onStop: stop,
        onStart: start,
        audioContext
    }
}